const request = require('request')
const fs = require('fs')
const path = require('path')
const { convert } = require('convert-svg-to-png');
const jszip = require('jszip')

/**
 * 
 * @param {Array} page 页面的json对象
 * @param {Number} width 宽
 * @param {Number} height 高
 * @param {Number} dpi 
 * @param {string} unit 单位
 */
async function getSvgHtml({page, width, height, dpi = 300, unit = 'mm'}) {
    dpi = unit === 'mm' ? (dpi / 25.4) : 1
    var viewWidth = width * dpi
    var viewHeight = height * dpi
    // console.log(`dip:${dpi}, viewWidth:${viewWidth}, viewHeight: ${viewHeight}, unit: ${unit}`)
    var images = [] // 存储所有的图片链接
    var _html = `
            <svg width="${200}" height="${200 * (height / width)}" 
            viewBox="0 0 ${viewWidth} ${viewHeight}"
            style="background:#fff"
            xmlns="http://www.w3.org/2000/svg" 
            version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">`
    page.forEach(json => {
        if ( json.type !== 'text' ) {
            // console.log(json.key)
            var reg = /(xlink:)?href=".*?"/ig
            var keyword = json._html.match(reg)
            if (keyword && Array.isArray(keyword)) {
                keyword.forEach(key => {
                    var imgPath = key.replace(/(xlink:href=|")/ig, '')
                    if (imgPath.indexOf("img") !== -1) {
                        var href = imgPath
                        if (imgPath.indexOf("http") === -1) {
                            json._html = json._html.replace(href, 'http:' + href)
                            imgPath = 'http:' + imgPath
                        }
                        images.push(imgPath)
                    }
                })
            }
        }
        if (json.type != 'Masking') { // 不是刀版
            if (json.type == 'text') {
                let reg = /(fill|stroke)=rgb\(.*?\)/ig;
                json._html = json._html.replace(reg, function (val) {
                    let arr = val.split('=')
                    val = arr[0] + '="' + arr[1] + '"'
                    return val
                })
                json._html.replace(/(stroke-linecap="round"|stroke-linejoin="round")/ig, '')
            }

            //补全阿里印的域名
            if (json.type === 'image' || json.type === 'background' || json.type === 'adsorb') {
                var _aliyin = /(http:|https:)*\/\/img.aliyin.com/ig;
                json._html = json._html.replace(_aliyin, 'http://img.aliyin.com')
            }

            _html += `<g ${json.transform ? 'transform="' + json.transform + '"': ''} opacity="${json.opacity || 1}">
                        <g ${json.rotation ? 'transform="' + json.rotation + '"': ''}>
                            <svg width="${json.width}" height="${json.height}" 
                            ${json.viewbox ? 'viewBox="' + json.viewbox + '"': ''}
                            preserveAspectRatio="none"
                            xmlns="http://www.w3.org/2000/svg" 
                            version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
                                ${json._html || ''}
                            </svg>
                        </g>
                    </g>`
        } else {
            if (json._html) {
                _html += `
                    <g style="pointer-events: none;">
                        ${json._html}
                    </g>
                `
            }
        }

        
    })
    _html += '</svg>'
    _html = _html.replace(/<g id="outBloodLine">.*?<\/g>/, '')
    _html = _html.replace(/<path id="outBloodLine".*?<\/path>/, '')

    
    /**
     * 将图片链接转换成base64
     */

    // console.log(images)
    var html = await Promise.all(Array.from(images).map(imgPath => {
        return new Promise(resolve => {
            // console.log(imgPath)
            getImage(imgPath, './public/pdf/bg/')
            .then(base64Img => {
                _html = _html.replace(imgPath, base64Img)
                resolve(base64Img)
            })
        })
    }))
    .then(data => {
        return {
            html: _html,
            images: data
        }
    })
    return html
}

function getImage(imgPath, dirPath) {
     return new Promise((resolve, reject) => {
        var img = path.resolve(`${dirPath}${Math.random().toString(36).slice(-8)}.png`)
        var file = fs.createWriteStream(img)
        file.on('finish', function () {
            resolve(img)
        })
        request(imgPath).pipe(file)
    })
}

/**
 * 图片转base64
 * @param {String} imgPath 图片路径
 * @param {String} dirPath 路径
 * @returns {Promise}  
 */
function img2base64(imgPath, dirPath) { 
    // console.log(imgPath)
    return new Promise((resolve, reject) => {
        // var img = path.resolve(`./public/pdf/bg/${new Date().getTime()}.png`)
        var img = path.resolve(`${dirPath}${Math.random().toString(36).slice(-8)}.png`)
        var file = fs.createWriteStream(img)
        file.on('finish', function () {
            /**
             * 1.读取文件的buffer
             * 2.buffer转base64
             */
            var buff = fs.readFileSync(img)
            var base64Img = "data:image/png;base64," + buff.toString('base64')
            resolve(base64Img)
        })
        request(imgPath).pipe(file)
    })
}

exports.getSvgHtml = getSvgHtml
exports.img2base64 = img2base64
/**
 * 删除文件夹下所有文件
 * @param {String} path 删除的文件夹路径
 */
function delDir(path){
    let files = [];
    if(fs.existsSync(path)){
        files = fs.readdirSync(path);
        files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()){
                delDir(curPath); //递归删除文件夹
            } else {
                fs.unlinkSync(curPath); //删除文件
            }
        });
        // fs.rmdirSync(path) // 删除文件夹
    }
}
exports.delDir = delDir


/**
 * 分析svg内容的img链接
 */

 exports.getSvgImage = async function(svg) {
    var reg = /(xlink:)?href=".*?"/ig
    var images = []
    var keyword = svg.match(reg)
    if (keyword) {
        for(var i = 0; i < keyword.length; i++) {
            var imgPath = keyword[i].replace(/(xlink:href=|")/ig, '')
            images.push(imgPath)
        }
    }
    var result = await Promise.all(Array.from(images).map(imgPath => {
        return new Promise(resolve => {
            img2base64(imgPath, './public/png/').then(img => {
                resolve(img)
            })
        })
    }))
    .then(newImages => {
        newImages.forEach((item, i) => {
            svg = svg.replace(images[i], item)
        })
        var name = Math.random().toString(36).slice(-8) 
        // console.log(name )
        fs.writeFileSync(path.resolve(`./public/thumb/${name}.svg`), svg)
        return {svg: path.resolve(`./public/thumb/${name}.svg`), images: newImages, name}
    })
    return result
 }


 /**
  * 根据filter重新生成图片
  * 
  */



function againProductionImg(svg, json) {
    return new Promise(async (resolve) => {
        var buff = await convert(svg, {width: json.width})
        resolve(buff)
    })
}

function getPDFImg(imgInfo, dirPath) {
    return new Promise(async (resolve, reject) => {
        var img = path.resolve(`${dirPath}${Math.random().toString(36).slice(-8)}.png`)
        if (imgInfo.json.isFilter) {
            var json = imgInfo.json
            var svg = ` <svg width="${json.width}" height="${json.height}" 
                            ${json.viewbox ? 'viewBox="' + json.viewbox + '"': ''}
                            preserveAspectRatio="none"
                            xmlns="http://www.w3.org/2000/svg" 
                            version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
                                ${json._html || ''}
                            </svg> `
            againProductionImg(svg, json)
            .then(buff => {
                var file = fs.createWriteStream(img)
                file.on('finish', function () {
                    resolve(img)
                })
                file.on('open', () => {
                    file.write(buff);
                    file.end();
                });
            })
        } else {
            var file = fs.createWriteStream(img)
            file.on('finish', function () {
                resolve(img)
            })
            console.log(imgInfo.imgPath, '下载时的图片')
            request(imgInfo.imgPath).pipe(file)
        }
   })
}




 /**
 * 
 * @param {Array} page 页面的json对象
 * @param {Number} width 宽
 * @param {Number} height 高
 * @param {Number} dpi 
 * @param {string} unit 单位
 */
exports.productionPDfSVG = async function({list, info, ratio}) {
    var images = [] // 存储所有的图片链接
    var _html = `
            <svg width="${200}" height="${200 * ratio}" 
            viewBox="0 0 ${info.pxwidth} ${info.pxheight}"
            style="background:#fff"
            xmlns="http://www.w3.org/2000/svg" 
            version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">`
    list.forEach(json => {
        //补全阿里印的域名
        if (json.type === 'image' || json.type === 'background' || json.type === 'adsorb') {
            var _aliyin = /(http:|https:)*\/\/img.aliyin.com/ig;
            json._html = json._html.replace(_aliyin, 'http://img.aliyin.com')
            json._html = json._html.replace('!w800.src', '')
        }
        if ( json.type !== 'text' ) {
            // console.log(json.key)
            json.isFilter = json.key && json.key.filters ? true : false
            var reg = /(xlink:)href=("|').*?('|")/ig
            var keyword = json._html.match(reg)
            if (keyword && Array.isArray(keyword)) {
                keyword = Array.from(new Set(keyword))
                keyword.forEach(key => {
                    var imgPath = key.replace(/(xlink:href=|"|'|href=)/ig, '')
                    if (imgPath.indexOf("img") !== -1) {
                        var href = imgPath
                        if (imgPath.indexOf("http") === -1) {
                            json._html = json._html.replace(href, 'http:' + href)
                            imgPath = 'http:' + imgPath
                        }
                        images.push({imgPath, json})
                    }
                })
            }
        }

        if (json.type != 'Masking') { // 不是刀版
            if (json.type == 'text') {
                let reg = /(fill|stroke)=rgb\(.*?\)/ig;
                json._html = json._html.replace(reg, function (val) {
                    let arr = val.split('=')
                    val = arr[0] + '="' + arr[1] + '"'
                    return val
                })
                json._html.replace(/(stroke-linecap="round"|stroke-linejoin="round")/ig, '')
            }

            

            _html += `<g ${json.transform ? 'transform="' + json.transform + '"': ''} opacity="${json.opacity || 1}">
                        <g ${json.rotation ? 'transform="' + json.rotation + '"': ''}>
                            <svg width="${json.width}" height="${json.height}" 
                            ${json.viewbox ? 'viewBox="' + json.viewbox + '"': ''}
                            preserveAspectRatio="none"
                            xmlns="http://www.w3.org/2000/svg" 
                            version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
                                ${json._html || ''}
                            </svg>
                        </g>
                    </g>`
        } else {
            if (json._html) {
                _html += `
                    <g style="pointer-events: none;">
                        ${json._html}
                    </g>
                `
            }
        }
       
    })
    _html += '</svg>'
    _html = _html.replace(/<g id="outBloodLine">.*?<\/g>/, '')
    _html = _html.replace(/<path id="outBloodLine".*?<\/path>/, '')

    
    /**
     * 将图片链接转换成base64
     */

    // console.log(images)
    var html = await Promise.all(Array.from(images).map(imgInfo => {
        return new Promise(resolve => {
            // console.log(imgInfo)
            getPDFImg(imgInfo, './public/pdf/bg/')
            .then(newImgPath => {
                _html = _html.replace(imgInfo.imgPath, newImgPath)
               
                resolve(newImgPath)
            })
        })
    }))
    .then(data => {
        var filterReg1 = /filter="url\(.*?\)"/ig
        var filterReg2 = /<filter id=".+?<\/filter>/ig
        _html = _html.replace(/\n/ig, ' ')
        _html = _html.replace(filterReg1, '')
        _html = _html.replace(filterReg2, '')
        return {
            html: _html,
            images: data
        }
    })
    return html
}